/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package shmallarchitect.faces.util;

import java.util.List;
import javax.faces.model.SelectItem;
import shmallarchitect.jpa.entities.Owner;
import shmallarchitect.jpa.jsf.OwnerController;

/**
 *
 * @author jaccus
 */
class OwnerUtil {

    static void copyProperties(Owner newOwner, Owner owner) {
        owner.setEmail(newOwner.getEmail());
        owner.setName(newOwner.getName());
        owner.setPhone(newOwner.getPhone());
        owner.setId(newOwner.getId());
    }

    public static Object addNew(Owner newOwner) {
        if (!alreadyExists(newOwner.getName())) {
            try {
                OwnerController uc = new OwnerController();
                Owner owner = uc.getOwner();
                copyProperties(newOwner, owner);
                uc.create();
                owner.setId(getOwnerIdByName(owner.getName()));
                return owner.getName();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;

    }

    public static long getOwnerIdByName(String name) {
        OwnerController uc = new OwnerController();
        SelectItem[] ownerItems = uc.getOwnerItemsAvailableSelectMany();

//        List<Owner> OwnerForUser = new LinkedList<Gallery>();

        for (SelectItem ownerItem : ownerItems) {
            final Owner owner = (Owner) ownerItem.getValue();
            if (owner.getName().equals(name)) {
                return owner.getId();
            }
        }
        return -1;
    }

    private static boolean alreadyExists(String name) {
        OwnerController oc = new OwnerController();
        SelectItem[] items = oc.getOwnerItemsAvailableSelectMany();
        for (int i = 0; i < items.length; i++) {
            Owner owner = (Owner) items[i].getValue();
            if (owner.getName().equals(name)) {
                return true;
            }
        }
        return false;
    }
}
